using System;
using Microsoft.SPOT.Hardware;
using Gadgeteer;

/*
 * Original Gadgeteer framework Copyright (c) Microsoft Corporation. (http://gadgeteer.codeplex.com/)
 * 
 * Gadgeteer Light made by Stefan Thoolen (http://gadgeteerlight.codeplex.com/)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace SecretLabs.NETMF.Hardware
{
    /// <summary>Wrapper for a PWM output port</summary>
    public class PWMOut : PWMOutProvider
    {
        /// <summary>The actual PWM output port</summary>
        private Microsoft.SPOT.Hardware.PWM _port = null;

        /// <summary>Local active value</summary>
        private bool _Active = false;

        /// <summary>Sets/gets if the PWM is active</summary>
        public override bool Active
        {
            get { return this._Active; }
            set
            {
                this._Active = value;
                if (value) this._port.Start();
                else this._port.Stop();
            }
        }

        /// <summary>Creates a new PWM output port</summary>
        /// <param name="socket">The socket on which the port exists</param>
        /// <param name="pin">The pin #</param>
        public override void Init(int socket, int pin)
        {
            this._port = new Microsoft.SPOT.Hardware.PWM(NetduinoShieldBase.GetPWM(socket, pin), 100, 1, false);
        }

        /// <summary>Sets the frequency and dutycycle</summary>
        /// <param name="frequency">frequency</param>
        /// <param name="dutyCycle">dutycycle</param>
        public override void Set(int frequency, byte dutyCycle)
        {
            float period = (1 / frequency) * 1000000000; // multiply to get nano seconds
            float hightime = period * dutyCycle;
            this.SetPulse((uint)period, (uint)hightime);
        }

        /// <summary>Sets the period and hightime</summary>
        /// <param name="period_ns">period</param>
        /// <param name="highTime_ns">hightime</param>
        public override void SetPulse(uint period_ns, uint highTime_ns)
        {
            // Netduino precision is in micro seconds, not nano seconds
            float period_micro = period_ns / 1000;
            float highTime_micro = highTime_ns / 1000;
            this._port.Duration = (uint)highTime_micro;
            this._port.Period = (uint)period_micro;
        }
    }
}